package com.tas.service.impl;

import com.tas.manager.AsyncMethodManager;
import com.tas.pojo.AsyncMethodHolder;
import com.tas.service.IStrategyService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.util.RunUtil;
import org.noear.solon.data.tran.TranListener;
import org.noear.solon.data.tran.TranUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * 先保存数据库，再执行异步任务
 * @author kevin
 */
@Component
public class DirectAsyncService implements IStrategyService {

  @Inject
  AsyncMethodManager asyncMethodManager;
  /**
   * 保存并执行异步任务
   * @param asyncMethod 执行的方法
   * @param params 任务参数
   * @return
   */
  @Override
  public Boolean execute(String asyncMethod, Object[] params) {

    //保存到数据库
    System.out.println(params);

    //异步任务
    if(TranUtils.inTrans()){
      //事务提交后执行
      TranUtils.listen(new TranListener() {
        @Override
        public void afterCommit() {
          doExecute(asyncMethod, params);
        }
      });
    }else{
      //没有这事务环境下直接异步执行
      doExecute(asyncMethod, params);
    }
    return true;
  }
  private void doExecute(String asyncMethod, Object[] params) {
    RunUtil.async(new Runnable() {
      @Override
      public void run() {
        AsyncMethodHolder methodHolder = asyncMethodManager.getMethod(asyncMethod);
        if(null == methodHolder){
          System.out.println("获取真正执行的方法错误，没获取到。" + asyncMethod);
          return;
        }

        System.out.println("真正执行：" + asyncMethod + " " + params);
        try {
          methodHolder.getMethod().invoke(methodHolder.getBean().raw(true), params);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });

  }
}
